import { ref, computed } from "vue";
import { ElMessage } from "element-plus";
import { useLcdContrastStore } from "@/store/modules/hmi/lcd-contrast.store";
import { useErrorHandler } from "@/composables/useErrorHandler";

/**
 * 液晶对比度 Composable
 */
export function useLcdContrast() {
  // Store
  const lcdContrastStore = useLcdContrastStore();

  // 错误处理
  const { handleError, withErrorHandling } = useErrorHandler();

  // 本地状态
  const localContrast = ref<number>(0);
  const refreshing = ref<boolean>(false);
  const updating = ref<boolean>(false);

  // 计算属性
  const isReady = computed(() => lcdContrastStore.isReady);
  const currentContrast = computed(() => lcdContrastStore.currentContrast);
  const isLoading = computed(() => lcdContrastStore.isLoading || refreshing.value);
  const isUpdating = computed(() => lcdContrastStore.isUpdating || updating.value);

  /**
   * 同步本地对比度值
   */
  const syncLocalContrast = () => {
    localContrast.value = lcdContrastStore.getCurrentContrast();
  };

  /**
   * 刷新液晶对比度
   * @param cpu CPU 编号
   */
  const refreshLcdContrast = async (cpu: number = 1) => {
    refreshing.value = true;

    try {
      await lcdContrastStore.fetchLcdContrast(cpu);
      syncLocalContrast();
      // ElMessage.success("液晶对比度刷新成功");
    } catch (error: any) {
      handleError(error, "刷新液晶对比度");
    } finally {
      refreshing.value = false;
    }
  };

  /**
   * 更新液晶对比度
   * @param cpu CPU 编号
   * @param contrast 对比度值
   */
  const updateLcdContrast = async (cpu: number = 1, contrast?: number) => {
    const contrastToUpdate = contrast !== undefined ? contrast : localContrast.value;

    // 验证数据
    const validation = lcdContrastStore.validateContrast(contrastToUpdate);
    if (!validation.isValid) {
      ElMessage.error(`数据验证失败：${validation.errors.join(", ")}`);
      return false;
    }

    updating.value = true;

    try {
      const result = await lcdContrastStore.updateLcdContrast(cpu, contrastToUpdate);

      if ("status" in result && result.status === "Success") {
        ElMessage.success("液晶对比度更新成功");
        syncLocalContrast();
        return true;
      } else if ("error" in result) {
        ElMessage.error(`液晶对比度更新失败：${result.message || result.error}`);
        return false;
      }

      return true;
    } catch (error: any) {
      handleError(error, "更新液晶对比度");
      return false;
    } finally {
      updating.value = false;
    }
  };

  /**
   * 重置本地对比度值
   */
  const resetLocalContrast = () => {
    syncLocalContrast();
  };

  /**
   * 验证对比度值
   * @param contrast 对比度值
   */
  const validateContrast = (contrast?: number) => {
    const contrastToValidate = contrast !== undefined ? contrast : localContrast.value;
    return lcdContrastStore.validateContrast(contrastToValidate);
  };

  /**
   * 设置对比度值
   * @param contrast 对比度值
   */
  const setLocalContrast = (contrast: number) => {
    const validation = validateContrast(contrast);
    if (validation.isValid) {
      localContrast.value = contrast;
    } else {
      ElMessage.warning(`对比度值无效：${validation.errors.join(", ")}`);
    }
  };

  /**
   * 初始化液晶对比度
   * @param cpu CPU 编号
   */
  const initLcdContrast = async (cpu: number = 1) => {
    if (lcdContrastStore.isReady) {
      syncLocalContrast();
      return;
    }

    try {
      await refreshLcdContrast(cpu);
    } catch (error: any) {
      handleError(error, "初始化液晶对比度");
    }
  };

  /**
   * 重置更新结果
   */
  const resetUpdateResult = () => {
    lcdContrastStore.resetUpdateResult();
  };

  /**
   * 获取最后更新结果
   */
  const getLastUpdateResult = () => {
    return lcdContrastStore.lastUpdateResult;
  };

  return {
    // 状态
    localContrast,
    isReady,
    currentContrast,
    isLoading,
    isUpdating,
    refreshing,
    updating,

    // 方法
    syncLocalContrast,
    refreshLcdContrast,
    updateLcdContrast,
    resetLocalContrast,
    validateContrast,
    setLocalContrast,
    initLcdContrast,
    resetUpdateResult,
    getLastUpdateResult,
  };
}
